package com.anxuan.agent.chatmemory;

import com.anxuan.agent.converter.MessageConverter;
import com.anxuan.agent.domain.ChatMessage;
import com.anxuan.agent.service.ChatMessageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import org.objenesis.strategy.StdInstantiatorStrategy;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 基于文件持久化的对话记忆
 */
public class MysqlBasedChatMemory implements ChatMemory {


    private final ChatMessageService chatMessageService;


    // 构造对象时，指定文件保存目录
    public MysqlBasedChatMemory(ChatMessageService chatMessageService) {
        this.chatMessageService = chatMessageService;
    }

    @Override
    public void add(String conversationId, List<Message> messages) {

        List<ChatMessage> chatMessages = messages.stream()
                .map(message -> MessageConverter.toChatMessage(message, conversationId))
                .toList();

        chatMessageService.saveBatch(chatMessages);

    }

    @Override
    public List<Message> get(String conversationId, int lastN) {
        List<ChatMessage> list = chatMessageService.lambdaQuery()
                .eq(ChatMessage::getConversationId, conversationId)
                .last(lastN > 0, "limit " + lastN)
                .orderByAsc(ChatMessage::getCreateTime)
                .list();
        return list.stream().map(MessageConverter::toMessage).collect(Collectors.toList());
    }

    @Override
    public void clear(String conversationId) {
        chatMessageService.lambdaUpdate()
                .eq(ChatMessage::getConversationId, conversationId)
                .remove();

    }

}
